package 对demo4_1的测试;

import java.util.Arrays;
import java.util.Comparator;

class Student implements Comparable<Student>{
    public String name;
    public int age;

    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }

    public int compareTo(Student o) {
        return this.age - o.age;
    }
}

//优点  对类的侵入性 不强
class AgeComparator implements Comparator<Student> {
    @Override
    public int compare(Student o1, Student o2) {
        return o1.age - o2.age;
    }
}
class NameComparator implements Comparator<Student> {
    @Override
    public int compare(Student o1, Student o2) {
        return o1.name.compareTo( o2.name) ;
    }
}

public class Test {

    public static void main(String[] args) {
        Student student1 = new Student("zhangsan", 10);
        Student student2 = new Student("lisi", 15);

        Student[] students = new Student[] {
                new Student("张三", 15),
                new Student("李四", 12),
                new Student("王五", 18),
                new Student("aaa", 16)
        };

        AgeComparator ageComparator = new AgeComparator();
        System.out.println(ageComparator.compare(student1, student2));

        NameComparator nameComparator = new NameComparator();
        System.out.println(nameComparator.compare(student1, student2));

        Arrays.sort(students, new AgeComparator());
        System.out.println(Arrays.toString(students));
    }
}

